//
//  CHChatViewController.m
//  ChildHoodStemp
//
//  Created by 日东 罗 on 13-10-5.
//
//
#import "CHChatViewController.h"
#import "MicroDef.h"
#import "UIUtil.h"
#import "QBImagePickerController.h"
#import "ChatToolMoreView.h"
#import "WZsenderMoneyViewController.h"
#import "ChildHoodMessage.h"
//#import "CHSThemeManager.h"
#import "UIImageView+WebCache.h"
#import "IMFileManagerController.h"
#import "ChildHoodService.h"
#import "CHSAudioPlayer.h"
#import "ISTThemeLabel.h"
#import <MessageUI/MessageUI.h>
#import "MBProgressHUD+WZ.h"
#import "MobilePhoneController.h"
#import "IMFowardController.h"
#import "WZNavigationController.h"
#import "CGroupMemberMgr.h"
#import "CContactMgr.h"
#import "CGroupMemberModel.h"
#import "CXmppRequestMgr.h"
#import "CaptureViewController.h"
#import "MapViewController.h"
#import "JKAlertDialog.h"
@interface CHChatViewController ()<ChatMoreViewDelegate,ChatToolDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TouchTableViewDelegate,QBImagePickerControllerDelegate, IMFileManagerControllerDelegate,MapViewControllerDelegate, MFMessageComposeViewControllerDelegate>
@property(nonatomic)BOOL firstOpen;
@property(nonatomic,copy) NSString *type;
@end

@implementation CHChatViewController
@synthesize tableView = _tableView;
@synthesize delegate = _delegate;
@synthesize dataSource = _dataSource;
@synthesize messages = _messages;

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self  name:ChatToolBarMoved object:nil];
    
    self.delegate = nil;
    self.dataSource = nil;
}
- (id)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

#pragma mark - Initialization
- (void)setup
{
    //    CGSize size = self.view.frame.size;
    
    CGRect tableFrame = CGRectMake(0.0f, 0.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT-114);
    //    NSLog(@"%@tableFrame",NSStringFromCGRect(tableFrame));
    _tableView = [[TouchTable alloc] initWithFrame:tableFrame style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    //	_tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.touchDelegate = self;
    _tableView.decelerationRate = 0.7;
    _tableView.showsVerticalScrollIndicator = YES;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatToolBarMoved:) name:ChatToolBarMoved object:nil];
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendChatMessage:) name:SendChatMessage object:nil];
    
}

-(void)tableView:(UITableView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    _chatToolBar.proToolHeight = _chatToolBar.contentText.frame.size.height;
    CGRect fra = _chatToolBar.frame;
    if (fra.origin.y == HARDWARE_SCREEN_HEIGHT-64-_chatToolBar.frame.size.height) {
        return;
    }
    [_chatToolBar reSetChatTool];
}

//bug 6107 fixed by 荣则兵

-(BOOL)isNeedScrollToBottom
{
    NSArray *array = [self.tableView indexPathsForVisibleRows];
    for(NSIndexPath *index in array)
    {
        if(index.row == self.messages.count - 1)
        {
            return YES;
        }
        
    }
    return NO;
}


-(void)resetChatTool
{
    [_chatToolBar reSetChatTool];
    BOOL isScroll = [self isNeedScrollToBottom];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:_chatToolBar.animateDuration];
    [UIView setAnimationCurve:_chatToolBar.animateCurve];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    CGRect fra = self.tableView.frame;
    fra.size.height = HARDWARE_SCREEN_HEIGHT - 64 - _chatToolBar.frame.size.height;
    [self.tableView setFrame:fra];
    if (isScroll) {
        [self scrollToBottomAnimated:NO];
    }
    [UIView commitAnimations];
}

-(void)chatToolBarMoved:(NSNotification*)noti
{
   
    CGFloat movedHeight = [noti.object floatValue];
    BOOL isScroll = [self isNeedScrollToBottom];
     if(self.chatToolBar.isMoreViewShow)
     {
         isScroll = NO;
         return;
     }
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:_chatToolBar.animateDuration];
    [UIView setAnimationCurve:_chatToolBar.animateCurve];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    
    CGRect fra = self.tableView.frame;
    if (movedHeight>=0) {
        //上移时设置
        fra.size.height = _chatToolBar.frame.origin.y;
    }else
    {
        //返回时设置
        fra.size.height = _chatToolBar.frame.origin.y;
    }
    [self.tableView setFrame:fra];
    
    //     NSLog(@"%@",NSStringFromCGRect(self.tableView.frame));
    if (isScroll) {
        [self scrollToBottomAnimated:NO];
    }
    [UIView commitAnimations];
    
    
}

#pragma mark ChatToolBarDelegate
-(void)sendChatMessage:(NSNotification*)noti
{
    NSString* log = (NSString*)noti.object;
    if (self.delegate && [self.delegate respondsToSelector:@selector(sendTextMessage:)]) {
        [self.delegate sendTextMessage:log];
    }
}

-(void) sendMsg:(NSString *)txtMsg
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(sendTextMessage:)]) {
        [self.delegate sendTextMessage:txtMsg];
    }
}

//- (void)contentTextViewTextDidChangeWithText:(NSString *)text
//{
//    if ([self.delegate respondsToSelector:@selector(contentTextViewTextDidChangeWithText:)]) {
//        [self.delegate contentTextViewTextDidChangeWithText:text];
//    }
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setBackgroundColor:RGBCOLOR(242, 245, 247)];
    
    //设置聊天背景图
    //    NSDictionary *chatBackgroundDict = [[CHSThemeManager sharedManager] currentChatBackgroundInfo];
    //    if (chatBackgroundDict != nil) {
    //        //添加用户选择的聊天背景
    //        UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT)];
    //        backgroundImageView.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetHeight(self.view.frame) - (IsIOS7 ? 64 : 44) - HARDWARE_SCREEN_HEIGHT / 2);
    //        NSString *imgName = chatBackgroundDict[ChatBackgroundId];
    ////        if (HARDWARE_SCREEN_HEIGHT <= 568) {
    ////        }
    ////        else if (HARDWARE_SCREEN_HEIGHT == 667 ) {
    ////           imgName = [imgName stringByReplacingOccurrencesOfString:@".jpg" withString:@"-750.jpg"];
    ////        }else{
    ////            imgName = [imgName stringByReplacingOccurrencesOfString:@".jpg" withString:@"-1242.jpg"];
    ////        }
    //        backgroundImageView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@.png",imgName]]];
    ////        backgroundImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.png",imgName]];
    //        [self.view addSubview:backgroundImageView];
    //    }
    self.firstOpen = YES;
    [self setup];
}


- (void)viewWillAppear:(BOOL)animated
{
    //    [self scrollToBottomAnimated:NO];
    [super viewWillAppear:animated];
    _chatToolBar = [ChatToolBar defaultChatToolBar];
    //    _chatToolBar.backgroundColor = RedColor;
    [_chatToolBar setChattoolDelegate:self];
    [self.view addSubview:_chatToolBar];
    [self.view bringSubviewToFront:_chatToolBar];
    _emoView = [EmotionView defaultEmoView];
    [self.view addSubview:_emoView];
    
    
    ChatToolMoreView* moreView = [ChatToolMoreView defaultMoreView];
    [moreView setMoreViewDelegate:self];
    [self.view addSubview:moreView];
    
    
    if ([self isNeedScrollToBottom]) {
        
        [self scrollToBottomAnimated:NO];
    }
    
    //NSLog(@"%@",NSStringFromCGRect(self.tableView.frame));
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_6_1
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
#else
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
#endif
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self setEditing:NO animated:YES];
    //    [self resetChatTool];
    _chatToolBar.proToolHeight = 0;
    _chatToolBar = [ChatToolBar defaultChatToolBar];
    
    //bug6095 fixed by 荣则兵
    //    [_chatToolBar.contentText setText:@""];
    [_chatToolBar removeFromSuperview];
    _emoView = [EmotionView defaultEmoView];
    [_emoView removeFromSuperview];
    ChatToolMoreView* moreView = [ChatToolMoreView defaultMoreView];
    [moreView removeFromSuperview];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:ChatToolBarMoved object:nil];
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:SendChatMessage object:nil];
    
}


#pragma mark - View rotation
- (BOOL)shouldAutorotate
{
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self.tableView reloadData];
    [self.tableView setNeedsLayout];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messages.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0){
        if (self.isShowSection) {
            return 30.0f;
        } else {
            return 5.0f;
        }
    };
    return 0.01f;
}

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {
    
    if(section == 0){
        if (self.isShowSection) {
            UILabel* liaotianLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH,30.0f)];
            liaotianLabel.backgroundColor =[UIColor clearColor];
            liaotianLabel.text = @"没有更早的聊天记录了";
            liaotianLabel.textColor = [UIColor blackColor];
            liaotianLabel.font = [UIFont systemFontOfSize:15.0f];
            liaotianLabel.numberOfLines = 0;
            liaotianLabel.textAlignment = NSTextAlignmentCenter;
            return liaotianLabel;
            
        } else {
            UIView *view = [[UIView alloc] init];
            view.backgroundColor = ClearColor;
            return view;
        }
    }
    return nil;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CHBubbleMessageType type = [self.delegate messageTypeForRowAtIndexPath:indexPath];
    CHBubbleStyle bubbleStyle = [self.delegate messageStyleForRowAtIndexPath:indexPath];
    BOOL ismap = [self.delegate ismapForRowAtIndexPath:indexPath];
    CHAvatarStyle avatarStyle = [self.delegate avatarStyle];
    ChildHoodMessage* msg = [self.messages objectAtIndex:indexPath.row];
    //    NSLog(@"bubbleStyle==%zd    %zd",bubbleStyle,msg.messageDBID);
    BOOL hasTimestamp = [self shouldHaveTimestampForRowAtIndexPath:indexPath];
    BOOL isNotice = [self.dataSource isNoticeForRowAtIndexPath:indexPath];
    BOOL hasSendeName = NO;
    if (M_ISSTRNULL(msg.fromName)) {
        hasSendeName = NO;
    } else {
        hasSendeName = YES;
    }
    NSString *CellID = [NSString stringWithFormat:@"MessageCell_%d_%d_%d_%d_%d", type, bubbleStyle, hasTimestamp,isNotice,hasSendeName];
    
    
    CHBubbleMessageCell *cell = (CHBubbleMessageCell *)[tableView dequeueReusableCellWithIdentifier:CellID];
    
    if(!cell)
    {
        
        cell = [[CHBubbleMessageCell alloc] initWithBubbleType:type
                                                   bubbleStyle:bubbleStyle
                                                   avatarStyle:avatarStyle
                                                  hasTimestamp:hasTimestamp
                                                      isNotice:isNotice isHasSenderName:hasSendeName reuseIdentifier:CellID ismap:ismap];
        [cell setBackgroundColor:tableView.backgroundColor];
        //        [cell.avatarView addTarget:self action:@selector(jumpToDetailInfoView:) forControlEvents:UIControlEventTouchUpInside];
    }
    cell.cellIndexPath = indexPath;
    cell.delegate = self;
    cell.messageList = self.messages;
    cell.chidMessage = msg;
    
    [cell setMemoryID:[self.dataSource memoryIDForRowAtIndexPath:indexPath]];
    if(hasTimestamp)
    {
        [cell setTimestamp:[self.dataSource timestampForRowAtIndexPath:indexPath]];
    }
    
    switch (type) {
        case CHBubbleMessageTypeReceived:
            [cell setAvatarImage:[self.dataSource avatarImageURIForReceivedMessageRowAtIndexPath:indexPath]];
            break;
            
        case CHBubbleMessageTypeSended:
            [cell setAvatarImage:[self.dataSource avatarImageURIForSendedMessageRowAtIndexPath:indexPath]];
            break;
    }
    
    [cell setName:[self.dataSource senderNameForRowAtIndexPath:indexPath]];
    [cell setTitle:[self.dataSource senderTitleForRowAtIndexPath:indexPath]];
    switch (bubbleStyle) {
        case CHBubbleStyleText:
        {
            //            cell.lable赋值和是否发送成功
            [cell setMessage:[self.dataSource textForRowAtIndexPath:indexPath] withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath]];
            break;
        }
        case CHBubbleStyleVoice:
        {
            //            NSLog(@"%zd",msg.isPlayed);
            [cell setIndexPathForVoice];
            [cell setVoice:[self.dataSource voiceURIForRowAtIndexPath:indexPath]
                 totalTime:[self.dataSource voiceTimeForRowAtIndexPath:indexPath]
                    isRead:msg.isPlayed
                withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath] andProcess:msg.progressReport
                  fileName:[self.dataSource fileNameForRowAtIndexPath:indexPath]
                    fileId:[self.dataSource fileIdForRowAtIndexPath:indexPath]
                  chatType:[self.dataSource chatTypeForRowAtIndexPath:indexPath] childMessage:self.messages[indexPath.row]];
            break;
        }
        case CHBubbleStylePicture:
        {
            NSArray *tmpArray = [self.dataSource pictureURIArrayForRowAtIndexPath:indexPath];
            NSInteger count = [tmpArray count];
            if (count >= 2) {
                [cell setPicture:[tmpArray objectAtIndex:0]
                         nextURI:[tmpArray objectAtIndex:1]
                      withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath] andProcess:msg.progressReport
                        fileName:[self.dataSource fileNameForRowAtIndexPath:indexPath]
                          fileId:[self.dataSource fileIdForRowAtIndexPath:indexPath]
                        chatType:[self.dataSource chatTypeForRowAtIndexPath:indexPath] childMessage:self.messages[indexPath.row]];
            }
            else
            {
                [cell setPicture:nil nextURI:nil withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath] andProcess:msg.progressReport
                        fileName:[self.dataSource fileNameForRowAtIndexPath:indexPath]
                          fileId:[self.dataSource fileIdForRowAtIndexPath:indexPath]
                        chatType:[self.dataSource chatTypeForRowAtIndexPath:indexPath] childMessage:self.messages[indexPath.row]];
            }
            break;
        }
        case CHBubbleStyleVideo:
        {
            [cell setVideo:nil withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath] andProcess:msg.progressReport fileName:[self.dataSource fileNameForRowAtIndexPath:indexPath] fileId:[self.dataSource fileIdForRowAtIndexPath:indexPath] chatType:[self.dataSource chatTypeForRowAtIndexPath:indexPath] chileMessage:self.messages[indexPath.row]];
            break;
        }
        case CHBubbleStyleRedPacket:
        {
            ChildHoodMessage *message = self.messages[indexPath.row];
            [cell setRedPacketInfo:message.messageContent withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath]];
        }
            break;
        case CHBubbleStyleFile:
        {
            [cell setFileWithStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath] andProcess:msg.progressReport
                           fileName:[self.dataSource fileNameForRowAtIndexPath:indexPath]
                             fileId:[self.dataSource fileIdForRowAtIndexPath:indexPath]
                           chatType:[self.dataSource chatTypeForRowAtIndexPath:indexPath] childMessage:self.messages[indexPath.row]];
        }
            break;
        case CHBubbleStyleEmoticon:
        {
            break;
        }
        case CHBubbleStyleShke:
        {
            [cell setMessage:[self.dataSource textForRowAtIndexPath:indexPath] withStatus:[self.dataSource messageStatusForRowAtIndexPath:indexPath]];
            break;
            
        }
        default:
            break;
    }
    [cell setMessageStatus:msg.messageStatus];
    return cell;
}


#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CHBubbleStyle bubbleStyle = [self.delegate messageStyleForRowAtIndexPath:indexPath];
    ChildHoodMessage *message = [self.messages objectAtIndex:indexPath.row];
    MessageSendType type  = message.messageStatus;
    CGFloat cellheight = 0;
    if (type == kMessageUserMute) {
        cellheight = SendAlert_Label_Height;
    }
    BOOL flag = [self shouldHaveTimestampForRowAtIndexPath:indexPath];
    
    BOOL hasSendeName = NO;
    if (M_ISSTRNULL(message.fromName)) {
        hasSendeName = NO;
    } else {
        hasSendeName = YES;
    }
    
    
    
    if (bubbleStyle == CHBubbleStylePicture || bubbleStyle == CHBubbleStyleFile || bubbleStyle == CHBubbleStyleRedPacket)
    {
        CGFloat timestampHeight = flag ? (TIMESTAMP_LABEL_HEIGHT + 2*INSET_HEIGHT) : 0.0f;
        CGFloat hasSenderNameHeight = hasSendeName ? SENDERNAME_LABEL_HEIGHT : 0.0f;
        cellheight += timestampHeight + hasSenderNameHeight + INSET_HEIGHT + kCHAvatarSize + INSET_HEIGHT + SENDERNAME_LABEL_HEIGHT + SENDERTITLE_LABEL_HEIGHT + INSET_HEIGHT;
        cellheight += 60;
    }
    else if (bubbleStyle == CHBubbleStyleVideo)
    {
        CGFloat timestampHeight = flag ? (TIMESTAMP_LABEL_HEIGHT + 2*INSET_HEIGHT) : 0.0f;
        CGFloat hasSenderNameHeight = hasSendeName ? SENDERNAME_LABEL_HEIGHT : 0.0f;
        cellheight += timestampHeight + hasSenderNameHeight + INSET_HEIGHT + kCHAvatarSize + INSET_HEIGHT + SENDERNAME_LABEL_HEIGHT + SENDERTITLE_LABEL_HEIGHT + INSET_HEIGHT;
        cellheight += 100;
    }
    else
    {
        cellheight +=[CHBubbleMessageCell neededHeightForText:[self.dataSource textForRowAtIndexPath:indexPath]
                                                    timestamp:flag isHasSenderName:hasSendeName];
    }
    return cellheight;
}

#pragma mark - Messages view controller
- (BOOL)shouldHaveTimestampForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch ([self.delegate timestampPolicy]) {
        case CHMessagesViewTimestampPolicyAll:
            return YES;
            
        case CHMessagesViewTimestampPolicyAlternating:
            return indexPath.row % 2 == 0;
            
        case CHMessagesViewTimestampPolicyEveryThree:
            return indexPath.row % 3 == 0;
            
        case CHMessagesViewTimestampPolicyEveryFive:
            return indexPath.row % 5 == 0;
            
        case CHMessagesViewTimestampPolicyCustom:
            if([self.delegate respondsToSelector:@selector(hasTimestampForRowAtIndexPath:)])
                return [self.delegate hasTimestampForRowAtIndexPath:indexPath];
            
        default:
            return NO;
    }
}

- (void)setBackgroundColor:(UIColor *)color
{
    self.view.backgroundColor = color;
    self.tableView.backgroundColor = color;
    self.tableView.separatorColor = color;
}

- (void)scrollToBottomAnimated:(BOOL)animated
{
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    
    if(rows > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows-1 inSection:0]
                              atScrollPosition:UITableViewScrollPositionBottom
                                      animated:animated];
    }
}

#pragma mark --ChatMoreViewDelegate--
-(void)selectPicFromAlbum
{
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.maximumNumberOfSelection = 10;
    imagePickerController.maxSelectedCount = 10;
    imagePickerController.previewText = @"预览";
    imagePickerController.oprationText = @"发送";
    //  CHSNavigationController *navigationController = [[CHSNavigationController alloc] initWithRootViewController:imagePickerController];
    [self.navigationController pushViewController:imagePickerController animated:YES];//:navigationController animated:YES completion:NULL];
    //[imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    
    //    }];
}
-(void)didselectVideofromAlbum
{
    self.type = @"video";
    UIImagePickerController *controller = [[UIImagePickerController alloc] init];
    [controller setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    controller.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
    [controller setDelegate:self];
    [self presentViewController:controller animated:YES completion:nil];
}
-(void)didSelectMoney
{
    WZsenderMoneyViewController *mvc = [[WZsenderMoneyViewController alloc]init];
    [self.navigationController pushViewController:mvc animated:YES];
    mvc.contact = _member;
    mvc.group = _group;
}
-(void)takePhotosWithCamera
{
    self.type = @"camera";
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"未获得授权使用摄像头" message:@"请在iOS设置->隐私->相机中打开"];
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            
        }];
        [alert show];
        return;
        
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        [imagePickerController setDelegate:self];
        
        [imagePickerController setEditing:YES];
        [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
        [self presentViewController:imagePickerController animated:YES completion:nil];
        
    }else
    {
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.maximumNumberOfSelection = 10;
        imagePickerController.maxSelectedCount = 10;
        imagePickerController.previewText = @"预览";
        imagePickerController.oprationText = @"发送";
        
        //  CHSNavigationController *navigationController = [[CHSNavigationController alloc] initWithRootViewController:imagePickerController];
        [self.navigationController pushViewController:imagePickerController animated:YES];//:navigationController animated:YES completion:NULL];
        //[imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
    
    //    }];
    
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    __weak typeof (self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    if ([_type isEqualToString:@"camera"]) {
        UIImage *aImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        if (_delegate && [_delegate respondsToSelector:@selector(sendImageMessage:index:)]) {
            [self.delegate sendImageMessage:aImg index:0];
        }
    }
    if ([_type isEqualToString:@"video"]) {
        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSData *data = [NSData dataWithContentsOfURL:videoURL];
        NSString *videoSizeMessage = [NSString stringWithFormat:@"视频压缩后文件大小为%.2fM,确定要发送吗?",data.length/1024.0/1024.0];
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"提醒" message:videoSizeMessage];
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            [weakSelf sendVideoMessage:videoURL];
        }];
        [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
            
        }];
        [alert show];
    }
    
    
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingMediaWithInfos:(id)info
{
    
    if (imagePickerController.allowsMultipleSelection) {
        NSArray *mediaInfoArray = (NSArray *)info;
        NSInteger count = mediaInfoArray.count;
        for (int i = 0; i < count; i++) {
            NSMutableDictionary *aDic = [mediaInfoArray objectAtIndex:i];
            UIImage *aImg = [aDic objectForKey:@"UIImagePickerControllerOriginalImage"];
            [self.delegate sendImageMessage:aImg index:i];
        }
    } else {
        // NSDictionary *mediaInfo = (NSDictionary *)info;
        //            NSLog(@"Selected: %@", mediaInfo);
    }
    
    
    
}

//bug fixed by lixu 8860
- (void)didGetGroupMembers:(NSNotification *)notice
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPGETGROUPMEMBERS object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPGETDISCUSSIONMEMLIST object:nil];
    [UIUtil hideMBProgressViewForView:self.view];
    [self didSelectMessage];
}
//bug fixed by lixu 8860
- (void)didSelectMessage
{
    if (self.group) {
        NSMutableArray *numberArray = [NSMutableArray array];
        NSArray *array = [[CGroupMemberMgr alloc] loadAllGroupMemberByGroupID:self.group.GroupId];
        if (array.count != self.group.UserNum) {
            [[CXmppRequestMgr shareInstance] getGroupMembersWithGroup:self.group];
            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didGetGroupMembers:) name:K_XMPPGETDISCUSSIONMEMLIST object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didGetGroupMembers:) name:K_XMPPGETGROUPMEMBERS object:nil];
            [UIUtil addMBProgressViewTitle:@"加载中..." inView:self.view alpha:1.0 failureTitle:@"加载失败"];
        }
        else
        {
            CContactModel *current = [[[CContactMgr alloc]init] loadCurContact];
            for (CGroupMemberModel *member in array) {
                CContactModel *contact = [[CContactMgr alloc] loadNotDelContactWithUserId:member.UserId];
                //bug 9266 fixed by lixu
                if (!M_ISSTRNULL(contact.MobileTelephone) && ![contact.MobileTelephone isEqualToString:current.MobileTelephone]) {
                    [numberArray addObject:contact.MobileTelephone];
                    
                }
            }
            if (self.group.UserNum -1 == numberArray.count) {
                MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
                
                
                // 2. 设置短信内容
                // 1) 收件人
                controller.recipients = numberArray;
                // 2) 短信内容
                //            controller.body = @"给您拜个晚年，祝您晚年快乐！";
                
                // 3) 设置代理
                controller.messageComposeDelegate = self;
                
                // 3. 显示短信控制器
                //            [self.navigationController pushViewController:controller animated:YES];
                [self presentViewController:controller animated:YES completion:nil];
            }
            else
            {
                MobilePhoneController *mob = [[MobilePhoneController alloc] init];
                mob.group = self.group;
                [self.navigationController pushViewController:mob animated:YES];
            }
            
        }
    }
    
    else {
        if (M_ISSTRNULL(self.member.MobileTelephone)) {
            [MBProgressHUD showError:@"该联系人未绑定手机"];
            //bug fixed 8858 by lixu
            return;
        }
        // 判断用户设备能否发送短信
        if (![MFMessageComposeViewController canSendText]) {
            return;
        }
        
        // 1. 实例化一个控制器
        MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
        
        
        // 2. 设置短信内容
        // 1) 收件人
        //bug 9263 fixed by lixu
        controller.recipients = @[M_ISSTRNULL(self.member.MobileTelephone)?@"":self.member.MobileTelephone];
        
        // 2) 短信内容
        //            controller.body = @"给您拜个晚年，祝您晚年快乐！";
        
        // 3) 设置代理
        controller.messageComposeDelegate = self;
        
        // 3. 显示短信控制器
        //            [self.navigationController pushViewController:controller animated:YES];
        [self presentViewController:controller animated:YES completion:nil];
        
        
    }
}


- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)didSelectLocation
{
    MapViewController *map = [[MapViewController alloc]init];
    map.MapManagerDelegate = self;
    [self.navigationController pushViewController:map animated:YES];
}
- (void)didSelectFile
{
    //    ChatToolMoreView* moreview = [ChatToolMoreView defaultMoreView];
    //    CGRect fra = moreview.frame;
    //    fra.origin.y = HARDWARE_SCREEN_HEIGHT - 64;
    //    [UIView animateWithDuration:0.2 animations:^{
    //        [moreview setFrame:fra];
    //    } completion:^(BOOL finished) {
    //        ChatToolBar *chatBar = [ChatToolBar defaultChatToolBar];
    //        chatBar.isMoreViewShow = !chatBar.isMoreViewShow;
    IMFileManagerController *managerVc = [[IMFileManagerController alloc] init];
    managerVc.fileManagerDelegate = self;
    //  CHSNavigationController *navigationController = [[CHSNavigationController alloc] initWithRootViewController:imagePickerController];
    [self.navigationController pushViewController:managerVc animated:YES];//:navigationController animated:YES completion:NULL];
    //[imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    
    //    }];
    
}
-(void)didselectVideofromCamera
{
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"未获得授权使用摄像头" message:@"请在iOS设置->隐私->相机中打开"];
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            
        }];
        [alert show];
        return;
        
    }
    
    CaptureViewController *captureViewCon = [[CaptureViewController alloc] initWithNibName:@"CaptureViewController" bundle:nil];
    __weak typeof(self) weakSelf = self;
    captureViewCon.URLBlock = ^(NSURL *url){
        weakSelf.videoUrl = url;
        [weakSelf sendVideoMessage:url];
    };
    [self presentViewController:captureViewCon animated:YES completion:nil];
    
}
- (void)fileManageControllerDidSendWithSelectedArray:(NSArray *)selectedArray
{
    [self sendFileWithArray:selectedArray];
}
-(void)sendVideoMessage:(NSURL*)url
{
    
}
- (void)sendFileWithArray:(NSArray *)array
{
    
}

- (void)imagePickerControllerDidCancels:(QBImagePickerController *)imagePickerController
{
    //    NSLog(@"Cancelled");
    [self dismissViewControllerAnimated:YES completion:NULL];
}



#pragma mark -CHBubbleMessageCellDelegate
- (void)menuControllerDidDeleteWithIndexpath:(NSIndexPath *)indexPath
{
    
}
//bug 8521 fixed by lixu
-(void)menuControllerDidForWardWithString:(NSString *)str
{
    [ChildHoodService defaultService].forwardText = str;
    [ChildHoodService defaultService].imgLocalFilePath = nil;
    [ChildHoodService defaultService].fileModel = nil;
    IMFowardController *foward = [[IMFowardController alloc] init];
    WZNavigationController *nav = [[WZNavigationController alloc] initWithRootViewController:foward];
    [self presentViewController:nav animated:YES completion:nil];
    
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.firstOpen) {
        cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1);
        [UIView animateWithDuration:0.3 animations:^{
            cell.layer.transform = CATransform3DMakeScale(1, 1, 1);
        } completion:^(BOOL finished) {
            if (finished) {
                self.firstOpen = NO;
            }
        }];
    }
}
#pragma mark --MapViewControllerDelegate
-(void)MapViewControlleDidSendWithImage:(UIImage *)mapImage lat:(double)lat lon:(double)lon
{
    if (_delegate && [_delegate respondsToSelector:@selector(sendMapImageMessage:withLat:andLon:)]) {
        [self.delegate sendMapImageMessage:mapImage withLat:lat andLon:lon];
    }
    
}
-(void)avartViewDidLongPressWithMessage:(ChildHoodMessage *)message AndLongPress:(UILongPressGestureRecognizer *)longPress
{
    if (M_ISSTRNULL(message.GroupId)) {
        return;
    }
    if(longPress.state != UIGestureRecognizerStateBegan)
        return;
    if (!self.chatToolBar.contentText.internalTextView.text) {
        self.chatToolBar.contentText.internalTextView.text = @"";
    }
    
    NSRange tempRange = [self.chatToolBar.contentText.internalTextView selectedRange];
    if (self.chatToolBar.textSelectRange.location<[self.chatToolBar.contentText.internalTextView selectedRange].location && self.chatToolBar.textSelectRange.location!=0) {
        tempRange = self.chatToolBar.textSelectRange;
    }
    
    NSString *firstStr = [self.chatToolBar.contentText.internalTextView.text substringToIndex:tempRange.location];
    NSString *lastStr =[self.chatToolBar.contentText.internalTextView.text substringFromIndex:tempRange.location];
    NSString *str = [NSString stringWithFormat:@"@%@ ",message.fromName];
    NSString *new_str = [NSString stringWithFormat:@"%@%@%@",firstStr,str,lastStr];
    NSRange range = NSMakeRange([[NSString stringWithFormat:@"%@%@",firstStr,str] length], 1);
    self.chatToolBar.textSelectRange = range;
    [self.chatToolBar.contentText setText:new_str];
}
@end
